package org.fcy.interceptors;

import org.fcy.utils.JwtUtil;
import org.fcy.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//创建登录拦截器
@Slf4j
@Component
public class LoginInterceptors implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头token
        String token = request.getHeader("Authorization");
        //验证 token
        try {
            String redisToken = stringRedisTemplate.opsForValue().get(token);
            log.info("redisToken:{}",redisToken);
            if(redisToken == null){
                throw new RuntimeException("Token not found in Redis");

            }
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //将数据保存到ThreadLocal
            ThreadLocalUtil.set(claims);

            //放行，如果没拿到token会捕捉异常
            return true;
        }catch (Exception e) {
            //设置响应状态码
            response.setStatus(401);
            return false;
        }
    }
}
